from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Board(models.Model):
    name = models.CharField('版块名称', max_length=100)
    description = models.TextField('版块描述')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    moderator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='moderated_boards')
    member_count = models.PositiveIntegerField('成员数量', default=0)
    topic_count = models.PositiveIntegerField('文章数量', default=0)
    image_url = models.URLField('版块图片', blank=True, null=True)
     
    class Meta:
        verbose_name = '论坛版块'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    # 新增统计方法
    def update_counts(self):
        self.topic_count = self.topics.count()
        self.member_count = User.objects.filter(topics__board=self).distinct().count()
        self.save()

class Topic(models.Model):
    title = models.CharField('标题', max_length=200)
    content = models.TextField('内容')
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='topics')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    views = models.PositiveIntegerField('浏览量', default=0)

    class Meta:
        verbose_name = '论坛主题'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return self.title

class Reply(models.Model):
    content = models.TextField('回复内容')
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='replies')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='replies')
    reply_to = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='replies_to')  # 修改为指向自身
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '论坛回复'
        verbose_name_plural = verbose_name
        ordering = ['created_at']

    def __str__(self):
        if self.reply_to:
            return f"回复@{self.reply_to.author.username}: {self.content[:20]}..."
        return f"回复: {self.content[:20]}..."
